<?php
namespace app\common\model;
use think\model\concern\SoftDelete;

class ProductCateModel extends BaseModel
{
    use SoftDelete;
    protected $table = 'product_cate';

    public static function getSelectList(array $where=['status'=>1],$api_field = 'apiNormalInfo')
    {
        $list = [];
        self::with(['linkChild'=>function($query)use($where){
            $query->where($where);
        }])->where(['pid'=>0])->where($where)->order('sort asc')->select()->each(function($item,$index)use(&$list,$api_field){
            $info = $item->$api_field();
            $info['child_list'] = [];
            $linkChild = $item->getRelation('linkChild');
            $child_list = [];
            if(!empty($linkChild)){
                foreach ($linkChild as $vo){
                    array_push($child_list,$vo->$api_field());
                }
            }
            $info['child_list'] = $child_list;
            array_push($list,$info);
        });
        return $list;
    }


    /**
     * 获取列表
     * @param array  $input_data
     * @throws
     * @return array
     * */
    public static function getPageData(array $input_data = [])
    {
        return self::getSelectList([],'apiFullInfo');
    }


    public static function handleSaveData(array $input_data = [])
    {
        if(empty($input_data['name'])) throw new \Exception('请输入名字');
        (new self())->actionAdd($input_data);
    }



    public function apiFullInfo()
    {
        return array_merge($this->apiNormalInfo(),[
            'is_index'=>$this['is_index'],
            'is_index_bool'=>$this['is_index']==1,

            'status'=>$this['status'],
            'sort_index'=>$this['sort_index'],
            'sort'=>$this['sort'],
            'status_name'=>self::getPropInfo('fields_status',$this['status'],'name'),
            'update_time'=>$this['update_time'],
        ]);
    }

    public function apiNormalInfo()
    {
        return [
            'id'=>(string)$this['id'],
            'pid'=>(string)(empty($this['pid'])?'':$this['pid']),
            'name'=>$this['name'],
            'img'=>$this['img'],
        ];
    }


    public function linkChild()
    {
        return $this->hasMany(self::class,'pid')->order('sort asc');
    }
}